@{
    ViewData["Title"] = "工序管理";
}

<div class="layui-card">
    <div class="layui-card-header">
        <h2 style="margin: 0; color: #1E9FFF;">
            <i class="layui-icon layui-icon-engine" style="font-size: 24px; margin-right: 8px;"></i>
            工序
        </h2>
    </div>
    <div class="layui-card-body">
        <!-- 搜索区域 -->
        <div class="layui-row layui-form" style="margin-bottom: 15px;">
            <div class="layui-col-md3">
                <label class="layui-form-label">工序编号:</label>
                <div class="layui-input-block">
                    <input type="text" id="processNumber" placeholder="请输入工序编号" class="layui-input">
                </div>
            </div>
            <div class="layui-col-md3">
                <div class="layui-input-block" style="margin-left: 0;">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="queryProcess()">
                        <i class="layui-icon layui-icon-search"></i> 查询
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="showAdvancedQuery()">
                        <i class="layui-icon layui-icon-search"></i> 高级查询
                    </button>
                </div>
            </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="layui-row" style="margin-bottom: 15px;">
            <div class="layui-col-md12">
                <div class="layui-btn-group" style="margin-right: 10px;">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="queryProcess()">
                        <i class="layui-icon layui-icon-search"></i> 查询
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="showAdvancedQuery()">
                        <i class="layui-icon layui-icon-search"></i> 高级查询
                    </button>
                </div>
                
                <div class="layui-btn-group" style="margin-right: 10px;">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="showNewProcess()">
                        <i class="layui-icon layui-icon-add-1"></i> 新建
                    </button>
                    <button type="button" class="layui-btn layui-btn-warm" onclick="editProcess()">
                        <i class="layui-icon layui-icon-edit"></i> 编辑
                    </button>
                    <button type="button" class="layui-btn layui-btn-danger" onclick="deleteProcess()">
                        <i class="layui-icon layui-icon-delete"></i> 删除
                    </button>
                </div>
                
                <div class="layui-btn-group" style="margin-right: 10px;">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="importProcess()">
                        <i class="layui-icon layui-icon-upload"></i> 导入
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" onclick="exportProcess()">
                        <i class="layui-icon layui-icon-download-circle"></i> 导出
                    </button>
                </div>
                
                <div class="layui-btn-group">
                    <button type="button" class="layui-btn layui-btn-primary" onclick="resetForm()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                    <button type="button" class="layui-btn layui-btn-danger" onclick="closeAdvancedQuery()">
                        <i class="layui-icon layui-icon-close"></i> 关闭
                    </button>
                </div>
                
                <!-- 调试按钮 -->
                <div class="layui-btn-group" style="margin-left: 10px;">
                    <button type="button" class="layui-btn layui-btn-warm" onclick="testMvcController()">
                        <i class="layui-icon layui-icon-search"></i> 测试MVC控制器
                    </button>
                    <button type="button" class="layui-btn layui-btn-warm" onclick="reloadRoles()">
                        <i class="layui-icon layui-icon-refresh"></i> 重新加载角色
                    </button>
                </div>
            </div>
        </div>

        <!-- 工序数据表格 -->
        <table class="layui-table" lay-even lay-skin="row" id="processTable">
            <thead>
                <tr>
                    <th style="width: 60px;">
                        <input type="checkbox" lay-skin="primary" lay-filter="allSelect">
                    </th>
                    <th onclick="sortTable('processNumber')" style="cursor: pointer;">
                        工序编号
                        <i class="layui-icon layui-icon-sort" id="sort-processNumber"></i>
                    </th>
                    <th onclick="sortTable('processName')" style="cursor: pointer;">
                        工序名称
                        <i class="layui-icon layui-icon-sort" id="sort-processName"></i>
                    </th>
                    <th>报工权限</th>
                    <th>报工数配比</th>
                    <th>不良品项列表</th>
                    <th onclick="sortTable('creatorDate')" style="cursor: pointer;">
                        创建时间
                        <i class="layui-icon layui-icon-sort" id="sort-creatorDate"></i>
                    </th>
                    <th>创建人</th>
                    <th>修改人</th>
                    <th onclick="sortTable('updatorDate')" style="cursor: pointer;">
                        修改时间
                        <i class="layui-icon layui-icon-sort" id="sort-updatorDate"></i>
                    </th>

                </tr>
            </thead>
            <tbody id="processTableBody">
                <!-- 数据将通过JavaScript动态加载 -->
            </tbody>
        </table>

        <!-- 分页 -->
        <div id="processPagination" class="layui-box layui-laypage layui-laypage-default"></div>
    </div>
</div>

<!-- 工序采集数据表格 -->
<div class="layui-card" style="margin-top: 20px;">
    <div class="layui-card-header">
        <h3 style="margin: 0; color: #1E9FFF;">
            <i class="layui-icon layui-icon-list" style="font-size: 18px; margin-right: 8px;"></i>
            工序采集数据
        </h3>
    </div>
    <div class="layui-card-body">
        <table class="layui-table" lay-even lay-skin="row" id="collectionDataTable">
            <thead>
                <tr>
                    <th style="width: 60px;">
                        <input type="checkbox" lay-skin="primary" lay-filter="allSelectCollection">
                    </th>
                    <th>工序</th>
                    <th><span style="color: red;">*</span>类型</th>
                    <th><span style="color: red;">*</span>名称</th>
                    <th>创建时间</th>
                    <th>创建人</th>
                    <th>修改人</th>
                    <th>修改时间</th>
                </tr>
            </thead>
            <tbody id="collectionDataTableBody">
                <tr>
                    <td colspan="8" style="text-align: center; color: #999;">暂无数据</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<!-- 高级查询弹窗 -->
<div id="advancedQueryModal" style="display: none;">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3 style="margin: 0; color: #1E9FFF;">
                <i class="layui-icon layui-icon-search" style="font-size: 18px; margin-right: 8px;"></i>
                高级查询
            </h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" id="advancedQueryForm">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工序编号:</label>
                            <div class="layui-input-block">
                                <input type="text" name="advancedProcessNumber" placeholder="请输入工序编号" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工序名称:</label>
                            <div class="layui-input-block">
                                <input type="text" name="advancedProcessName" placeholder="请输入工序名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">报工权限:</label>
                            <div class="layui-input-block">
                                <div id="advancedReportingPermissions" class="layui-input" style="min-height: 38px; padding: 5px; cursor: pointer;" onclick="showRoleSelector()">
                                    <span style="color: #999;">请选择报工权限</span>
                                </div>
                                <input type="hidden" name="advancedReportingPermissions" id="advancedReportingPermissionsValue">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">报工数配比:</label>
                            <div class="layui-input-inline" style="width: 45%;">
                                <input type="number" name="advancedReportingRatioStart" placeholder="开始" class="layui-input">
                            </div>
                            <span style="margin: 0 5px;">-</span>
                            <div class="layui-input-inline" style="width: 45%;">
                                <input type="number" name="advancedReportingRatioEnd" placeholder="结束" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">不良品项:</label>
                            <div class="layui-input-block">
                                <div id="advancedDefectiveItemList" class="layui-input" style="min-height: 38px; padding: 5px; cursor: pointer;" onclick="showAdvancedDefectiveSelector()">
                                    <span style="color: #999;">请选择不良品项</span>
                                </div>
                                <input type="hidden" name="advancedDefectiveItemList" id="advancedDefectiveItemListValue">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">测试字段1:</label>
                            <div class="layui-input-block">
                                <input type="text" name="advancedTestField1" placeholder="请输入测试字段1" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">测试字段2:</label>
                            <div class="layui-input-block">
                                <input type="text" name="advancedTestField2" placeholder="请输入测试字段2" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">创建时间:</label>
                            <div class="layui-input-inline" style="width: 45%;">
                                <input type="text" name="advancedCreationTimeStart" placeholder="开始时间" class="layui-input" readonly>
                            </div>
                            <span style="margin: 0 5px;">至</span>
                            <div class="layui-input-inline" style="width: 45%;">
                                <input type="text" name="advancedCreationTimeEnd" placeholder="结束时间" class="layui-input" readonly>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-form-item" style="margin-top: 30px; text-align: center;">
                    <div class="layui-input-block" style="margin-left: 0;">
                        <button type="button" class="layui-btn layui-btn-normal" onclick="advancedQuery()">
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="resetAdvancedQuery()">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                        <button type="button" class="layui-btn layui-btn-danger" onclick="closeAdvancedQuery()">
                            <i class="layui-icon layui-icon-close"></i> 关闭
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 不良品项选择弹窗 -->
<div id="defectiveSelectorModal" style="display: none; padding: 20px;">
    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">搜索:</label>
            <div class="layui-input-block">
                <input type="text" id="defectiveSearch" placeholder="输入不良品项编号或名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" onclick="searchDefective()">搜索</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeDefectiveSelector()">关闭</button>
            </div>
        </div>
    </div>
    <div id="defectiveList" style="max-height: 300px; overflow-y: auto;">
        <!-- 不良品项列表将通过JavaScript动态加载 -->
    </div>
</div>

<!-- 角色选择弹窗 -->
<div id="roleSelectorModal" style="display: none; padding: 20px;">
    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">选择角色:</label>
            <div class="layui-input-block">
                <div id="roleList" style="max-height: 300px; overflow-y: auto;">
                    <!-- 角色列表将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn layui-btn-normal" onclick="confirmRoleSelection()">确定</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeRoleSelector()">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 高级查询不良品项选择弹窗 -->
<div id="advancedDefectiveSelectorModal" style="display: none; padding: 20px;">
    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">搜索:</label>
            <div class="layui-input-block">
                <input type="text" id="advancedDefectiveSearch" placeholder="输入不良品项编号或名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" onclick="searchAdvancedDefective()">搜索</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeAdvancedDefectiveSelector()">关闭</button>
            </div>
        </div>
    </div>
    <div id="advancedDefectiveList" style="max-height: 300px; overflow-y: auto;">
        <!-- 不良品项列表将通过JavaScript动态加载 -->
    </div>
</div>

<!-- 新建工序弹窗 -->
<div id="newProcessModal" style="display: none;">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3 style="margin: 0; color: #1E9FFF;">
                <i class="layui-icon layui-icon-add-1" style="font-size: 18px; margin-right: 8px;"></i>
                工序(新建)
            </h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" id="newProcessForm">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工序编号:</label>
                            <div class="layui-input-block">
                                <input type="text" name="processNumber" placeholder="请输入,忽略将自动生成" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span style="color: red;">*</span>工序名称:</label>
                            <div class="layui-input-block">
                                <input type="text" name="processName" placeholder="工序名称" class="layui-input" required>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span style="color: red;">*</span>报工权限:</label>
                            <div class="layui-input-block">
                                <div id="newProcessReportingPermissions" class="layui-input" style="min-height: 38px; padding: 5px; cursor: pointer;" onclick="showNewProcessRoleSelector()">
                                    <span style="color: #999;">请选择报工权限</span>
                                </div>
                                <input type="hidden" name="reportingPermissions" id="newProcessReportingPermissionsValue">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span style="color: red;">*</span>报工数配比:</label>
                            <div class="layui-input-block">
                                <input type="number" name="reportingRatio" placeholder="报工数配比" class="layui-input" required>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">不良品项列表:</label>
                            <div class="layui-input-block">
                                <div id="newProcessDefectiveItemList" class="layui-input" style="min-height: 38px; padding: 5px; cursor: pointer;" onclick="showNewProcessDefectiveSelector()">
                                    <span style="color: #999;">请选择不良品项</span>
                                </div>
                                <input type="hidden" name="defectiveItemList" id="newProcessDefectiveItemListValue">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">测试字段1:</label>
                            <div class="layui-input-block">
                                <input type="text" name="testField1" placeholder="测试字段1" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">测试字段2:</label>
                            <div class="layui-input-block">
                                <input type="text" name="testField2" placeholder="测试字段2" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 工序采集数据 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">工序采集数据:</label>
                    <div class="layui-input-block">
                        <div class="layui-btn-group">
                            <button type="button" class="layui-btn layui-btn-sm" onclick="addCollectionDataRow()">
                                <i class="layui-icon layui-icon-add-1"></i> 添加行
                            </button>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="removeCollectionDataRow()">
                                <i class="layui-icon layui-icon-delete"></i> 删除行
                            </button>
                        </div>
                        <table class="layui-table" id="newProcessCollectionDataTable">
                            <thead>
                                <tr>
                                    <th style="width: 60px;">
                                        <input type="checkbox" lay-skin="primary" lay-filter="allSelectNewProcessCollectionData">
                                    </th>
                                    <th><span style="color: red;">*</span>类型</th>
                                    <th><span style="color: red;">*</span>名称</th>
                                </tr>
                            </thead>
                            <tbody id="newProcessCollectionDataTableBody">
                                <!-- 动态添加行 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div class="layui-form-item" style="margin-top: 30px; text-align: center;">
                    <div class="layui-input-block" style="margin-left: 0;">
                        <button type="button" class="layui-btn layui-btn-normal" onclick="saveNewProcess()">
                            <i class="layui-icon layui-icon-ok"></i> 保存
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="closeNewProcessModal()">
                            <i class="layui-icon layui-icon-close"></i> 关闭
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 新建工序角色选择弹窗 -->
<div id="newProcessRoleSelectorModal" style="display: none; padding: 20px;">
    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">选择角色:</label>
            <div class="layui-input-block">
                <div id="newProcessRoleList" style="max-height: 300px; overflow-y: auto;">
                    <!-- 角色列表将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn layui-btn-normal" onclick="confirmNewProcessRoleSelection()">确定</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeNewProcessRoleSelector()">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 新建工序不良品项选择弹窗 -->
<div id="newProcessDefectiveSelectorModal" style="display: none; padding: 20px;">
    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">搜索:</label>
            <div class="layui-input-block">
                <input type="text" id="newProcessDefectiveSearch" placeholder="输入不良品项编号或名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" onclick="searchNewProcessDefective()">搜索</button>
                <button type="button" class="layui-btn layui-btn-normal" onclick="confirmNewProcessDefectiveSelection()">确定</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeNewProcessDefectiveSelector()">关闭</button>
            </div>
        </div>
    </div>
    <div id="newProcessDefectiveList" style="max-height: 300px; overflow-y: auto;">
        <!-- 不良品项列表将通过JavaScript动态加载 -->
    </div>
</div>

<!-- 编辑工序弹窗 -->
<div id="editProcessModal" style="display: none;">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3 style="margin: 0; color: #1E9FFF;">
                <i class="layui-icon layui-icon-edit" style="font-size: 18px; margin-right: 8px;"></i>
                工序(编辑)
            </h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" id="editProcessForm">
                <input type="hidden" name="editProcessId" id="editProcessId">
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">工序编号:</label>
                            <div class="layui-input-block">
                                <input type="text" name="editProcessNumber" id="editProcessNumber" class="layui-input" readonly>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span style="color: red;">*</span>工序名称:</label>
                            <div class="layui-input-block">
                                <input type="text" name="editProcessName" id="editProcessName" placeholder="工序名称" class="layui-input" required>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span style="color: red;">*</span>报工权限:</label>
                            <div class="layui-input-block">
                                <div id="editProcessReportingPermissions" class="layui-input" style="min-height: 38px; padding: 5px; cursor: pointer;" onclick="showEditProcessRoleSelector()">
                                    <span style="color: #999;">请选择报工权限</span>
                                </div>
                                <input type="hidden" name="editReportingPermissions" id="editProcessReportingPermissionsValue">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><span style="color: red;">*</span>报工数配比:</label>
                            <div class="layui-input-block">
                                <input type="number" name="editReportingRatio" id="editReportingRatio" placeholder="报工数配比" class="layui-input" required>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">不良品项列表:</label>
                            <div class="layui-input-block">
                                <div id="editProcessDefectiveItemList" class="layui-input" style="min-height: 38px; padding: 5px; cursor: pointer;" onclick="showEditProcessDefectiveSelector()">
                                    <span style="color: #999;">请选择不良品项</span>
                                </div>
                                <input type="hidden" name="editDefectiveItemList" id="editProcessDefectiveItemListValue">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">测试字段1:</label>
                            <div class="layui-input-block">
                                <input type="text" name="editTestField1" id="editTestField1" placeholder="测试字段1" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row">
                    <div class="layui-col-md6">
                        <div class="layui-form-item">
                            <label class="layui-form-label">测试字段2:</label>
                            <div class="layui-input-block">
                                <input type="text" name="editTestField2" id="editTestField2" placeholder="测试字段2" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 工序采集数据 -->
                <div class="layui-form-item">
                    <label class="layui-form-label">工序采集数据:</label>
                    <div class="layui-input-block">
                        <div class="layui-btn-group">
                            <button type="button" class="layui-btn layui-btn-sm" onclick="addEditCollectionDataRow()">
                                <i class="layui-icon layui-icon-add-1"></i> 添加行
                            </button>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="removeEditCollectionDataRow()">
                                <i class="layui-icon layui-icon-delete"></i> 删除行
                            </button>
                        </div>
                        <table class="layui-table" id="editCollectionDataTable">
                            <thead>
                                <tr>
                                    <th style="width: 60px;">
                                        <input type="checkbox" lay-skin="primary" lay-filter="allSelectEditCollectionData">
                                    </th>
                                    <th><span style="color: red;">*</span>类型</th>
                                    <th><span style="color: red;">*</span>名称</th>
                                </tr>
                            </thead>
                            <tbody id="editCollectionDataTableBody">
                                <!-- 动态添加行 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div class="layui-form-item" style="margin-top: 30px; text-align: center;">
                    <div class="layui-input-block" style="margin-left: 0;">
                        <button type="button" class="layui-btn layui-btn-normal" onclick="saveEditProcess()">
                            <i class="layui-icon layui-icon-ok"></i> 保存
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="closeEditProcessModal()">
                            <i class="layui-icon layui-icon-close"></i> 关闭
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑工序角色选择弹窗 -->
<div id="editProcessRoleSelectorModal" style="display: none; padding: 20px;">
    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">选择角色:</label>
            <div class="layui-input-block">
                <div id="editProcessRoleList" style="max-height: 300px; overflow-y: auto;">
                    <!-- 角色列表将通过JavaScript动态加载 -->
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn layui-btn-normal" onclick="confirmEditProcessRoleSelection()">确定</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeEditProcessRoleSelector()">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑工序不良品项选择弹窗 -->
<div id="editProcessDefectiveSelectorModal" style="display: none; padding: 20px;">
    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">搜索:</label>
            <div class="layui-input-block">
                <input type="text" id="editProcessDefectiveSearch" placeholder="输入不良品项编号或名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" onclick="searchEditProcessDefective()">搜索</button>
                <button type="button" class="layui-btn layui-btn-normal" onclick="confirmEditProcessDefectiveSelection()">确定</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeEditProcessDefectiveSelector()">关闭</button>
            </div>
        </div>
    </div>
    <div id="editProcessDefectiveList" style="max-height: 300px; overflow-y: auto;">
        <!-- 不良品项列表将通过JavaScript动态加载 -->
    </div>
</div>

<script>
layui.use(['form', 'laydate', 'layer'], function(){
    var form = layui.form;
    var laydate = layui.laydate;
    var layer = layui.layer;
    
    // 将Layui模块暴露到全局作用域
    window.layui = layui;
    window.layer = layer;
    window.form = form;
    window.laydate = laydate;
    
    console.log('Layui模块加载完成:', {
        form: typeof form,
        laydate: typeof laydate,
        layer: typeof layer
    });
    
    // 初始化全局变量
    initializeVariables();
    
    // 初始化日期选择器
    laydate.render({
        elem: '#creationTimeStart',
        type: 'datetime'
    });
    
    laydate.render({
        elem: '#creationTimeEnd',
        type: 'datetime'
    });
    
    // 初始化高级查询弹窗中的日期选择器
    laydate.render({
        elem: 'input[name="advancedCreationTimeStart"]',
        type: 'datetime'
    });
    
    laydate.render({
        elem: 'input[name="advancedCreationTimeEnd"]',
        type: 'datetime'
    });
    
    // 初始化表单
    form.render();
    
    // 加载角色列表
    loadRoles();
    
    // 预加载不良品项数据
    preloadDefectiveData();
    
    // 页面加载完成后自动执行查询
    setTimeout(function() {
        // 加载工序数据
        loadProcessData();
    }, 100);
    
    // 确保角色数据加载完成
    setTimeout(function() {
        console.log('延迟检查角色数据:', roleData);
        console.log('全局角色数据:', window.roleData);
        console.log('角色数据长度:', roleData ? roleData.length : 'undefined');
        console.log('全局角色数据长度:', window.roleData ? window.roleData.length : 'undefined');
    }, 2000);
    
    // 添加全局测试函数
    window.testRoleData = function() {
        console.log('=== 角色数据测试 ===');
        console.log('roleData:', roleData);
        console.log('window.roleData:', window.roleData);
        console.log('roleData类型:', typeof roleData);
        console.log('roleData长度:', roleData ? roleData.length : 'undefined');
        if (roleData && roleData.length > 0) {
            roleData.forEach((role, index) => {
                console.log(`角色${index}:`, role);
            });
        }
        console.log('==================');
    };
    
    // 添加手动加载角色数据的函数
    window.reloadRoles = function() {
        console.log('手动重新加载角色数据...');
        loadRoles();
    };
    
    // 添加测试MVC控制器的方法
    window.testMvcController = function() {
        console.log('测试MVC控制器...');
        fetch('/Process/GetRoleAll')
            .then(response => {
                console.log('MVC控制器响应状态:', response.status);
                console.log('MVC控制器响应头:', response.headers);
                return response.text();
            })
            .then(data => {
                console.log('MVC控制器返回数据:', data);
                try {
                    var jsonData = JSON.parse(data);
                    console.log('解析后的JSON数据:', jsonData);
                } catch (e) {
                    console.log('数据不是有效的JSON格式');
                }
            })
            .catch(error => {
                console.error('MVC控制器调用失败:', error);
            });
    };
    
    // 首次加载后，默认选中第一条工序并加载其采集数据
    setTimeout(function() {
        var firstRow = document.querySelector('#processTableBody tr');
        if (firstRow) {
            var firstId = firstRow.getAttribute('data-process-id');
            if (firstId) {
                selectProcess(firstId);
            }
        }
    }, 500);
    
    // 添加Layui状态检查
    setTimeout(function() {
        console.log('=== Layui状态检查 ===');
        console.log('window.layui:', typeof window.layui);
        console.log('window.layer:', typeof window.layer);
        console.log('window.form:', typeof window.form);
        console.log('window.laydate:', typeof window.laydate);
        console.log('defectiveData:', defectiveData);
        console.log('roleData:', roleData);
        console.log('==================');
        
        // 如果Layui没有加载，尝试重新加载
        if (typeof window.layui === 'undefined') {
            console.warn('Layui未加载，尝试重新加载...');
            // 这里可以尝试重新加载Layui
        }
    }, 1000);
});

// 全局变量
var currentPage = 1;
var pageSize = 30;
var sortField = '';
var sortDirection = '';
var selectedProcessId = null;

// 多选相关全局变量
var selectedRoles = [];
var selectedDefectiveItems = [];
var advancedSelectedRoles = [];
var advancedSelectedDefectiveItems = [];
var roleData = []; // 存储角色数据
var defectiveData = []; // 存储不良品项数据

// 初始化函数
function initializeVariables() {
    // 确保变量正确初始化
    if (!advancedSelectedRoles) advancedSelectedRoles = [];
    if (!advancedSelectedDefectiveItems) advancedSelectedDefectiveItems = [];
    if (!roleData) roleData = [];
    if (!defectiveData) defectiveData = [];
}

// 加载角色列表
function loadRoles() {
    console.log('开始加载角色数据...');
    console.log('当前roleData:', roleData);
    console.log('当前window.roleData:', window.roleData);
    
    // 使用MVC控制器的GetRoleAll方法，避免跨域问题
    console.log('调用MVC控制器: /Process/GetRoleAll');
    fetch('/Process/GetRoleAll', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
        .then(response => {
            console.log('角色API响应状态:', response.status);
            console.log('角色API响应头:', response.headers);
            return response.json();
        })
        .then(data => {
            console.log('角色API返回数据:', data);
            console.log('数据类型:', typeof data);
            console.log('data.data类型:', typeof data.data);
            console.log('data.data长度:', data.data ? data.data.length : 'undefined');
            
            if (data.code === 200) {
                // 存储角色数据供后续使用
                roleData = data.data || [];
                console.log('原始角色数据:', roleData);
                console.log('原始角色数据长度:', roleData.length);
                
                // 检查每个角色的详细信息
                if (roleData.length > 0) {
                    roleData.forEach((role, index) => {
                        console.log(`角色${index}:`, role);
                        console.log(`角色${index} ID:`, role.id, '类型:', typeof role.id);
                        console.log(`角色${index} 名称:`, role.roleName);
                        console.log(`角色${index} 状态:`, role.isState);
                        console.log(`角色${index} 删除状态:`, role.isDeleted);
                    });
                }
                
                // 添加"所有人"选项
                if (!roleData.find(r => r.id === 0)) {
                    roleData.unshift({
                        id: 0,
                        roleName: '所有人',
                        isState: true,
                        isDeleted: false
                    });
                }
                
                console.log('最终角色数据:', roleData);
                console.log('最终角色数据长度:', roleData.length);
                
                // 强制更新全局变量
                window.roleData = roleData;
                
                // 验证数据是否正确设置
                console.log('设置后的roleData:', roleData);
                console.log('设置后的window.roleData:', window.roleData);
            } else {
                console.error('加载角色失败:', data.msg);
                // 确保至少有"所有人"选项
                roleData = [{
                    id: 0,
                    roleName: '所有人',
                    isState: true,
                    isDeleted: false
                }];
                window.roleData = roleData;
            }
        })
        .catch(error => {
            console.error('加载角色失败:', error);
            console.error('错误详情:', error.message);
            console.error('错误堆栈:', error.stack);
            
            // 尝试使用备用方法
            console.log('尝试使用备用方法加载角色数据...');
            
            // 确保至少有"所有人"选项
            roleData = [{
                id: 0,
                roleName: '所有人',
                isState: true,
                isDeleted: false
            }];
            window.roleData = roleData;
            
            // 3秒后重试
            setTimeout(function() {
                console.log('3秒后重试加载角色数据...');
                loadRoles();
            }, 3000);
        });
}

// 加载工序数据
function loadProcessData() {
    var queryData = {
        pageNumber: currentPage,
        pageSize: pageSize,
        processNumber: document.getElementById('processNumber').value,
        processName: '',
        reportingPermissions: '',
        reportingRatioStart: null,
        reportingRatioEnd: null,
        defectiveItemList: '',
        testField1: '',
        testField2: '',
        creationTimeStart: null,
        creationTimeEnd: null,
        sortField: sortField,
        sortDirection: sortDirection
    };
    
    fetch('http://localhost:5089/api/Process/query', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(queryData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            renderProcessTable(data.data);
            renderPagination(data.data);
        } else {
            layer.msg(data.msg || '查询失败');
        }
    })
    .catch(error => {
        console.error('查询失败:', error);
        layer.msg('查询失败');
    });
}

// 渲染工序表格
function renderProcessTable(data) {
    var tbody = document.getElementById('processTableBody');
    tbody.innerHTML = '';
    
    if (data.data && data.data.length > 0) {
        data.data.forEach((process, index) => {
            var row = document.createElement('tr');
            row.className = 'process-row';
            row.setAttribute('data-process-id', process.id);
            row.style.cursor = 'pointer';
            row.onmouseover = function() { this.style.backgroundColor = '#f2f2f2'; };
            row.onmouseout = function() { this.style.backgroundColor = ''; };
            row.onclick = function() { selectProcess(process.id); };
            
            row.innerHTML = `
                <td onclick="event.stopPropagation();">
                    <input type="checkbox" lay-skin="primary" lay-filter="processSelect" value="${process.id}">
                </td>
                <td>${process.processNumber}</td>
                <td>${process.processName}</td>
                <td>
                    ${formatReportingPermissions(process.reportingPermissions)}
                </td>
                <td>${process.reportingRatio}</td>
                <td>${formatDefectiveItemList(process.defectiveItemList, process.id)}</td>
                <td>${formatDateTime(process.creatorDate)}</td>
                <td>${process.creator}</td>
                <td>${process.updator || '-'}</td>
                <td>${process.updatorDate ? formatDateTime(process.updatorDate) : '-'}</td>
            `;
            
            tbody.appendChild(row);
        });
    } else {
        tbody.innerHTML = '<tr><td colspan="10" style="text-align: center; color: #999;">暂无数据</td></tr>';
    }
    
    // 重新渲染表单
    layui.form.render();
    
    // 默认选中第一行并加载采集数据
    setTimeout(function() {
        var firstRow = document.querySelector('#processTableBody tr');
        if (firstRow) {
            var firstId = firstRow.getAttribute('data-process-id');
            if (firstId) {
                selectProcess(firstId);
            }
        }
    }, 50);
}

// 渲染分页
function renderPagination(data) {
    var pagination = document.getElementById('processPagination');
    var totalPages = data.totalPages;
    var totalCount = data.totalCount;
    
    pagination.innerHTML = `
        <span>共 ${totalCount} 条</span>
        <select onchange="changePageSize(this.value)">
            <option value="30" ${pageSize === 30 ? 'selected' : ''}>30条/页</option>
            <option value="50" ${pageSize === 50 ? 'selected' : ''}>50条/页</option>
            <option value="100" ${pageSize === 100 ? 'selected' : ''}>100条/页</option>
        </select>
        <a href="javascript:;" onclick="goToPage(${currentPage - 1})" ${currentPage <= 1 ? 'style="color: #ccc;"' : ''}>&lt;</a>
        <span class="layui-laypage-curr">${currentPage}</span>
        <a href="javascript:;" onclick="goToPage(${currentPage + 1})" ${currentPage >= totalPages ? 'style="color: #ccc;"' : ''}>&gt;</a>
        <span>前往</span>
        <input type="text" value="${currentPage}" onchange="goToPage(this.value)" style="width: 50px; text-align: center;">
        <span>页</span>
    `;
}

// 选择工序
function selectProcess(processId) {
    console.log('选择工序，ID:', processId);
    selectedProcessId = processId;
    
    // 移除其他行的选中状态
    document.querySelectorAll('.process-row').forEach(row => {
        row.style.backgroundColor = '';
    });
    
    // 设置当前行选中状态
    var currentRow = document.querySelector(`tr[data-process-id="${processId}"]`);
    if (currentRow) {
        currentRow.style.backgroundColor = '#e6f3ff';
    }
    
    // 加载工序采集数据
    loadProcessCollectionData(processId);
}

// 加载工序采集数据
function loadProcessCollectionData(processId) {
	fetch(`http://localhost:5089/api/Process/collection-data/${processId}`)
		.then(response => response.json())
		.then(data => {
			if (data.code === 200) {
				renderCollectionDataTable(data.data);
			} else {
				layer.msg(data.msg || '查询失败');
			}
		})
		.catch(error => {
			console.error('查询失败:', error);
			layer.msg('查询失败');
		});
}

// 渲染工序采集数据表格
function renderCollectionDataTable(data) {
	var tbody = document.getElementById('collectionDataTableBody');
	tbody.innerHTML = '';
	
	if (data && data.length > 0) {
		data.forEach(item => {
			var row = document.createElement('tr');
			row.innerHTML = `
				<td>
					<input type="checkbox" lay-skin="primary" lay-filter="collectionSelect" value="${item.id}">
				</td>
				<td>${item.processName || item.processId || ''}</td>
				<td>${item.dataType || ''}</td>
				<td>${item.dataName || ''}</td>
				<td>${formatDateTime(item.creatorDate)}</td>
				<td>${item.creator || ''}</td>
				<td>${item.updator || '-'}</td>
				<td>${item.updatorDate ? formatDateTime(item.updatorDate) : '-'}</td>
			`;
			tbody.appendChild(row);
		});
	} else {
		tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: #999;">暂无数据</td></tr>';
	}
	
	// 重新渲染表单
	layui.form.render();
}

// 查询工序
function queryProcess() {
    currentPage = 1;
    loadProcessData();
}

// 高级查询
function showAdvancedQuery() {
    console.log('显示高级查询弹窗...');
    
    // 检查Layui是否可用
    if (typeof window.layui === 'undefined' && typeof layui === 'undefined') {
        console.warn('Layui未加载，使用备用弹窗方案');
        showFallbackAdvancedQuery();
        return;
    }
    
    // 使用更兼容的方式调用Layui
    try {
        var layuiInstance = window.layui || layui;
        layuiInstance.use(['layer'], function(){
            var layer = layuiInstance.layer;
            
            if (layer && typeof layer.open === 'function') {
                var index = layer.open({
                    type: 1,
                    title: '高级查询',
                    content: document.getElementById('advancedQueryModal'),
                    area: ['800px', '600px'],
                    maxmin: true,
                    resize: false,
                    success: function(layero, index) {
                        console.log('高级查询弹窗显示成功，索引:', index);
                        // 重新渲染表单
                        layuiInstance.form.render();
                        
                        // 重新初始化日期选择器
                        layuiInstance.laydate.render({
                            elem: 'input[name="advancedCreationTimeStart"]',
                            type: 'datetime'
                        });
                        layuiInstance.laydate.render({
                            elem: 'input[name="advancedCreationTimeEnd"]',
                            type: 'datetime'
                        });
                    },
                    end: function() {
                        console.log('高级查询弹窗关闭');
                        // 弹窗关闭后，确保隐藏原始DOM元素
                        var modal = document.getElementById('advancedQueryModal');
                        if (modal) {
                            modal.style.display = 'none';
                        }
                    }
                });
                
                console.log('高级查询弹窗索引:', index);
            } else {
                console.error('Layer模块不可用，使用备用弹窗方案');
                showFallbackAdvancedQuery();
            }
        });
    } catch (error) {
        console.error('显示弹窗失败:', error);
        console.warn('使用备用弹窗方案');
        showFallbackAdvancedQuery();
    }
}

// 执行高级查询
function advancedQuery() {
    // 获取高级查询表单数据
    var formData = new FormData(document.getElementById('advancedQueryForm'));
    var advancedData = {};
    
    for (var [key, value] of formData.entries()) {
        if (value) {
            // 移除"advanced"前缀并转换为小写
            var fieldName = key.replace('advanced', '').toLowerCase();
            advancedData[fieldName] = value;
        }
    }
    
    // 合并基础查询条件和高级查询条件
    var queryData = {
        pageNumber: 1,
        pageSize: pageSize,
        processNumber: advancedData.processnumber || document.getElementById('processNumber').value,
        processName: advancedData.processname || '',
        reportingPermissions: document.getElementById('advancedReportingPermissionsValue').value || '',
        reportingRatioStart: advancedData.reportingratiostart || null,
        reportingRatioEnd: advancedData.reportingratioend || null,
        defectiveItemList: document.getElementById('advancedDefectiveItemListValue').value || '',
        testField1: advancedData.testfield1 || '',
        testField2: advancedData.testfield2 || '',
        creationTimeStart: advancedData.creationtimestart || null,
        creationTimeEnd: advancedData.creationtimeend || null,
        sortField: sortField,
        sortDirection: sortDirection
    };
    
    // 更新基础查询表单的值
    if (advancedData.processnumber) document.getElementById('processNumber').value = advancedData.processnumber;
    
    // 执行查询
    currentPage = 1;
    loadProcessDataWithAdvancedQuery(queryData);
    
    // 关闭弹窗
    closeAdvancedQuery();
    
    // 显示提示信息
    layer.msg('高级查询已应用', {icon: 1});
}

// 使用高级查询条件加载数据
function loadProcessDataWithAdvancedQuery(queryData) {
    fetch('http://localhost:5089/api/Process/query', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(queryData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            renderProcessTable(data.data);
            renderPagination(data.data);
        } else {
            layer.msg(data.msg || '查询失败');
        }
    })
    .catch(error => {
        console.error('查询失败:', error);
        layer.msg('查询失败');
    });
}

// 重置高级查询
function resetAdvancedQuery() {
    document.getElementById('advancedQueryForm').reset();
    
    // 重置多选数据
    advancedSelectedRoles = [];
    advancedSelectedDefectiveItems = [];
    
    // 重置显示文本
    document.getElementById('advancedReportingPermissions').innerHTML = '<span style="color: #999;">请选择报工权限</span>';
    document.getElementById('advancedDefectiveItemList').innerHTML = '<span style="color: #999;">请选择不良品项</span>';
    
    // 重置隐藏字段
    document.getElementById('advancedReportingPermissionsValue').value = '';
    document.getElementById('advancedDefectiveItemListValue').value = '';
    
    layui.form.render();
}

// 关闭高级查询
function closeAdvancedQuery() {
    console.log('关闭高级查询弹窗...');
    
    // 使用Layui的layer模块关闭弹窗
    layui.use(['layer'], function(){
        var layer = layui.layer;
        
        // 获取当前打开的所有弹窗
        var openLayers = document.querySelectorAll('.layui-layer');
        if (openLayers.length > 0) {
            // 关闭最后一个弹窗（通常是当前弹窗）
            var lastLayer = openLayers[openLayers.length - 1];
            var layerIndex = lastLayer.getAttribute('times');
            if (layerIndex) {
                layer.close(layerIndex);
            }
        }
        
        // 确保隐藏原始DOM元素
        var modal = document.getElementById('advancedQueryModal');
        if (modal) {
            modal.style.display = 'none';
            modal.style.cssText = '';
        }
    });
}

// 显示不良品项选择器
function showDefectiveSelector() {
    var modal = document.getElementById('defectiveSelectorModal');
    modal.style.display = 'block';
    
    // 仅设置弹窗样式（不再创建遮罩层）
    modal.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        max-height: 80vh;
        overflow-y: auto;
    `;
    
    // 加载不良品项列表
    loadDefectiveList();
}

// 加载不良品项列表
function loadDefectiveList() {
    fetch('http://localhost:5089/api/Defective/GetPage?Index=1&Size=100')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderDefectiveList(data.pageData);
            } else {
                layer.msg(data.msg || '查询失败');
            }
        })
        .catch(error => {
            console.error('查询失败:', error);
            layer.msg('查询失败');
        });
}

// 渲染不良品项列表
function renderDefectiveList(data) {
    var container = document.getElementById('defectiveList');
    container.innerHTML = '';
    
    if (data && data.length > 0) {
        data.forEach(item => {
            var div = document.createElement('div');
            div.className = 'layui-form-item';
            div.style.padding = '10px';
            div.style.borderBottom = '1px solid #eee';
            div.style.cursor = 'pointer';
            div.onclick = function() { selectDefective(item); };
            div.onmouseover = function() { this.style.backgroundColor = '#f2f2f2'; };
            div.onmouseout = function() { this.style.backgroundColor = ''; };
            
            div.innerHTML = `
                <div style="font-weight: bold;">${item.defectiveCode || '无编号'}</div>
                <div style="color: #666;">${item.defectiveName}</div>
            `;
            
            container.appendChild(div);
        });
    } else {
        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
    }
}

// 选择不良品项
function selectDefective(item) {
    var displayText = `${item.defectiveCode || '无编号'} | ${item.defectiveName}`;
    document.getElementById('defectiveItemList').value = displayText;
    closeDefectiveSelector();
}

// 搜索不良品项
function searchDefective() {
    var searchText = document.getElementById('defectiveSearch').value;
    fetch(`/Process/GetDefectiveList?size=100&defectiveName=${encodeURIComponent(searchText)}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderDefectiveList(data.pageData);
            } else {
                layer.msg(data.msg || '查询失败');
            }
        })
        .catch(error => {
            console.error('查询失败:', error);
            layer.msg('查询失败');
        });
}

// 关闭不良品项选择器
function closeDefectiveSelector() {
    console.log('关闭不良品项选择器弹窗...');
    
    // 使用Layui的layer模块关闭弹窗
    layui.use(['layer'], function(){
        var layer = layui.layer;
        
        // 获取当前打开的所有弹窗
        var openLayers = document.querySelectorAll('.layui-layer');
        if (openLayers.length > 0) {
            // 关闭最后一个弹窗（通常是当前弹窗）
            var lastLayer = openLayers[openLayers.length - 1];
            var layerIndex = lastLayer.getAttribute('times');
            if (layerIndex) {
                layer.close(layerIndex);
            }
        }
        
        // 确保隐藏原始DOM元素
        var modal = document.getElementById('defectiveSelectorModal');
        if (modal) {
            modal.style.display = 'none';
        }
    });
}

// 排序表格
function sortTable(field) {
    if (sortField === field) {
        sortDirection = sortDirection === 'asc' ? 'desc' : 'asc';
    } else {
        sortField = field;
        sortDirection = 'asc';
    }
    
    // 更新排序图标
    updateSortIcons();
    
    // 重新加载数据
    loadProcessData();
}

// 更新排序图标
function updateSortIcons() {
    // 重置所有排序图标
    document.querySelectorAll('[id^="sort-"]').forEach(icon => {
        icon.className = 'layui-icon layui-icon-sort';
    });
    
    // 设置当前排序字段的图标
    if (sortField) {
        var currentIcon = document.getElementById(`sort-${sortField}`);
        if (currentIcon) {
            currentIcon.className = sortDirection === 'asc' ? 'layui-icon layui-icon-up' : 'layui-icon layui-icon-down';
        }
    }
}

// 分页相关函数
function goToPage(page) {
    if (page < 1) return;
    currentPage = page;
    loadProcessData();
}

function changePageSize(size) {
    pageSize = parseInt(size);
    currentPage = 1;
    loadProcessData();
}

// 重置表单
function resetForm() {
    document.getElementById('processNumber').value = '';
    
    // 重置排序
    sortField = '';
    sortDirection = '';
    updateSortIcons();
    
    // 重新加载数据
    currentPage = 1;
    loadProcessData();
}

// 其他功能函数（新建、编辑、删除、导入、导出）
function showNewProcess() {
    console.log('显示新建工序弹窗...');
    
    // 检查Layui是否可用
    if (typeof window.layui === 'undefined' && typeof layui === 'undefined') {
        console.warn('Layui未加载，使用备用弹窗方案');
        showFallbackNewProcess();
        return;
    }
    
    // 使用更兼容的方式调用Layui
    try {
        var layuiInstance = window.layui || layui;
        layuiInstance.use(['layer'], function(){
            var layer = layuiInstance.layer;
            
            if (layer && typeof layer.open === 'function') {
                var index = layer.open({
                    type: 1,
                    title: '工序(新建)',
                    content: document.getElementById('newProcessModal'),
                    area: ['1000px', '90vh'],
                    maxmin: true,
                    resize: false,
                    success: function(layero, index) {
                        console.log('新建工序弹窗显示成功，索引:', index);
                        // 初始化表单
                        resetNewProcessForm();
                        // 重新渲染表单
                        layuiInstance.form.render();
                    },
                    end: function() {
                        console.log('新建工序弹窗关闭');
                        // 弹窗关闭后，确保隐藏原始DOM元素
                        var modal = document.getElementById('newProcessModal');
                        if (modal) {
                            modal.style.display = 'none';
                        }
                    }
                });
                
                console.log('新建工序弹窗索引:', index);
            } else {
                console.error('Layer模块不可用，使用备用弹窗方案');
                showFallbackNewProcess();
            }
        });
    } catch (error) {
        console.error('显示弹窗失败:', error);
        console.warn('使用备用弹窗方案');
        showFallbackNewProcess();
    }
}

function editProcess() {
    if (!selectedProcessId) {
        layer.msg('请先选择要编辑的工序');
        return;
    }
    
    // 获取选中的工序数据
    var selectedRow = document.querySelector(`tr[data-process-id="${selectedProcessId}"]`);
    if (!selectedRow) {
        layer.msg('未找到选中的工序数据');
        return;
    }
    
    // 显示编辑弹窗
    showEditProcessModal(selectedProcessId);
}

function deleteProcess() {
    if (!selectedProcessId) {
        layer.msg('请先选择要删除的工序');
        return;
    }
    
    // 确认删除
    layer.confirm('确定要删除选中的工序吗？', {
        btn: ['确定', '取消']
    }, function(index) {
        // 执行删除
        executeDeleteProcess(selectedProcessId);
        layer.close(index);
    });
}

function executeDeleteProcess(processId) {
    // 这里应该调用删除API
    // 暂时显示提示信息
    layer.msg('删除功能需要后端API支持');
    
    // 实际删除时应该调用：
    // fetch(`http://localhost:5090/api/Process/Delete/${processId}`, {
    //     method: 'DELETE'
    // })
    // .then(response => response.json())
    // .then(data => {
    //     if (data.code === 200) {
    //         layer.msg('删除成功');
    //         loadProcessData(); // 刷新列表
    //     } else {
    //         layer.msg(data.msg || '删除失败');
    //     }
    // })
    // .catch(error => {
    //     console.error('删除失败:', error);
    //     layer.msg('删除失败');
    // });
}

function importProcess() {
    // 创建文件输入元素
    var fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.xlsx,.xls,.csv';
    fileInput.style.display = 'none';
    
    fileInput.onchange = function(e) {
        var file = e.target.files[0];
        if (file) {
            // 这里应该调用导入API
            layer.msg('导入功能需要后端API支持');
            
            // 实际导入时应该调用：
            // var formData = new FormData();
            // formData.append('file', file);
            // fetch('http://localhost:5090/api/Process/Import', {
            //     method: 'POST',
            //     body: formData
            // })
            // .then(response => response.json())
            // .then(data => {
            //     if (data.code === 200) {
            //         layer.msg('导入成功');
            //         loadProcessData(); // 刷新列表
            //     } else {
            //         layer.msg(data.msg || '导入失败');
            //     }
            // })
            // .catch(error => {
            //     console.error('导入失败:', error);
            //     layer.msg('导入失败');
            // });
        }
    };
    
    document.body.appendChild(fileInput);
    fileInput.click();
    document.body.removeChild(fileInput);
}

function exportProcess() {
    // 获取当前查询条件
    var queryData = {
        pageNumber: 1,
        pageSize: 10000, // 导出所有数据
        processNumber: document.getElementById('processNumber').value,
        processName: '',
        reportingPermissions: '',
        reportingRatioStart: null,
        reportingRatioEnd: null,
        defectiveItemList: '',
        testField1: '',
        testField2: '',
        creationTimeStart: null,
        creationTimeEnd: null,
        sortField: '',
        sortDirection: ''
    };
    
    // 这里应该调用导出API
    layer.msg('导出功能需要后端API支持');
    
    // 实际导出时应该调用：
    // fetch('http://localhost:5090/api/Process/Export', {
    //     method: 'POST',
    //     headers: {
    //         'Content-Type': 'application/json'
    //     },
    //     body: JSON.stringify(queryData)
    // })
    // .then(response => response.blob())
    // .then(blob => {
    //     // 创建下载链接
    //     var url = window.URL.createObjectURL(blob);
    //     var a = document.createElement('a');
    //     a.href = url;
    //     a.download = '工序数据_' + new Date().toISOString().slice(0, 10) + '.xlsx';
    //     document.body.appendChild(a);
    //     a.click();
    //     document.body.removeChild(a);
    //     window.URL.revokeObjectURL(url);
    //     layer.msg('导出成功');
    // })
    // .catch(error => {
    //     console.error('导出失败:', error);
    //     layer.msg('导出失败');
    // });
}

// 工具函数
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '-';
    var date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function formatReportingPermissions(permissionsStr) {
    if (!permissionsStr) return '';
    const ids = permissionsStr.split(',').map(s => s.trim()).filter(Boolean);
    if (ids.length === 0) return '';
    const labels = ids.map(id => {
        if (id === '0' || id === 0) return '<span class="layui-badge layui-bg-blue">所有人</span>';
        const role = (roleData || []).find(r => String(r.id) === String(id));
        const name = role ? role.roleName : id;
        return `<span class="layui-badge layui-bg-green">${name}</span>`;
    });
    return labels.join(' ');
}

function formatDefectiveItemList(defectiveItemList, processId) {
    if (!defectiveItemList) return '';
    
    try {
        // 确保defectiveData存在
        if (!defectiveData || !Array.isArray(defectiveData)) {
            console.warn('defectiveData未定义或不是数组，使用原始数据');
            // 如果内容过长，截断显示
            if (defectiveItemList.length > 50) {
                return defectiveItemList.substring(0, 50) + '...';
            }
            return defectiveItemList;
        }
        
        // 尝试解析JSON格式的不良品项列表
        let items = defectiveItemList;
        if (typeof defectiveItemList === 'string') {
            if (defectiveItemList.startsWith('[') && defectiveItemList.endsWith(']')) {
                try {
                    items = JSON.parse(defectiveItemList);
                } catch (e) {
                    console.warn('JSON解析失败，使用原始字符串:', e);
                    items = defectiveItemList;
                }
            } else if (defectiveItemList.includes(',')) {
                items = defectiveItemList.split(',');
            }
        }
        
        // 如果是数组，格式化显示
        if (Array.isArray(items)) {
            const displayItems = items.map(item => {
                // 查找对应的不良品项详情
                const defectiveItem = defectiveData.find(d => d.id == item || d.defectiveCode == item);
                if (defectiveItem) {
                    return `${defectiveItem.defectiveCode || '无编号'} | ${defectiveItem.defectiveName}`;
                }
                return item;
            });
            
            // 如果内容过长，截断显示
            const displayText = displayItems.join(', ');
            if (displayText.length > 50) {
                return displayText.substring(0, 50) + '...';
            }
            return displayText;
        }
    } catch (e) {
        console.error('格式化不良品项列表出错:', e);
    }
    
    // 如果内容过长，截断显示
    if (defectiveItemList.length > 50) {
        return defectiveItemList.substring(0, 50) + '...';
    }
    return defectiveItemList;
}

// 显示角色选择器
function showRoleSelector() {
    console.log('显示高级查询角色选择器');
    
    // 检查Layui是否可用
    if (typeof window.layui === 'undefined' && typeof layui === 'undefined') {
        console.warn('Layui未加载，使用备用弹窗方案');
        showFallbackModal('选择角色', document.getElementById('roleSelectorModal').innerHTML, '400px', '500px');
        loadRoleList();
        return;
    }
    
    // 使用更兼容的方式调用Layui
    try {
        var layuiInstance = window.layui || layui;
        layuiInstance.use(['layer'], function(){
            var layer = layuiInstance.layer;
            
            if (layer && typeof layer.open === 'function') {
                var index = layer.open({
                    type: 1,
                    title: '选择角色',
                    content: document.getElementById('roleSelectorModal'),
                    area: ['400px', '500px'],
                    maxmin: false,
                    resize: false,
                    success: function(layero, index) {
                        console.log('角色选择器弹窗显示成功，索引:', index);
                        // 加载角色列表
                        loadRoleList();
                    },
                    end: function() {
                        console.log('角色选择器弹窗关闭');
                        // 弹窗关闭后，确保隐藏原始DOM元素
                        var modal = document.getElementById('roleSelectorModal');
                        if (modal) {
                            modal.style.display = 'none';
                        }
                    }
                });
                
                console.log('角色选择器弹窗索引:', index);
            } else {
                console.error('Layer模块不可用，使用备用弹窗方案');
                showFallbackModal('选择角色', document.getElementById('roleSelectorModal').innerHTML, '400px', '500px');
                loadRoleList();
            }
        });
    } catch (error) {
        console.error('显示弹窗失败:', error);
        console.warn('使用备用弹窗方案');
        showFallbackModal('选择角色', document.getElementById('roleSelectorModal').innerHTML, '400px', '500px');
        loadRoleList();
    }
}

// 加载角色列表
function loadRoleList() {
    var container = document.getElementById('roleList');
    container.innerHTML = '';
    
    console.log('loadRoleList called, roleData:', roleData);
    console.log('window.roleData:', window.roleData);
    
    // 优先使用全局变量
    var currentRoleData = window.roleData || roleData || [];
    console.log('当前使用的角色数据:', currentRoleData);
    console.log('当前使用的角色数据长度:', currentRoleData ? currentRoleData.length : 'undefined');
    
    if (currentRoleData && currentRoleData.length > 0) {
        console.log('开始渲染角色列表...');
        currentRoleData.forEach((role, index) => {
            console.log(`处理角色${index}:`, role);
            console.log(`角色${index} ID:`, role.id, '类型:', typeof role.id);
            console.log(`角色${index} 名称:`, role.roleName);
            console.log(`角色${index} 状态:`, role.isState);
            console.log(`角色${index} 删除状态:`, role.isDeleted);
            
            // 检查角色是否应该显示
            var shouldShow = true;
            if (role.isState === false) {
                console.log(`角色${index} 状态为false，跳过`);
                shouldShow = false;
            }
            if (role.isDeleted === true) {
                console.log(`角色${index} 已删除，跳过`);
                shouldShow = false;
            }
            
            if (shouldShow) {
                console.log(`角色${index} 符合显示条件，创建DOM元素`);
                var div = document.createElement('div');
                div.className = 'layui-form-item';
                div.style.padding = '10px';
                div.style.borderBottom = '1px solid #eee';
                div.style.cursor = 'pointer';
                
                var checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.value = role.id;
                checkbox.checked = advancedSelectedRoles && advancedSelectedRoles.includes(role.id);
                checkbox.onchange = function() {
                    if (this.checked) {
                        if (!advancedSelectedRoles.includes(role.id)) {
                            advancedSelectedRoles.push(role.id);
                        }
                    } else {
                        advancedSelectedRoles = advancedSelectedRoles.filter(id => id !== role.id);
                    }
                };
                
                div.appendChild(checkbox);
                div.appendChild(document.createTextNode(' ' + (role.id === 0 ? '所有人' : role.roleName)));
                
                container.appendChild(div);
                console.log(`角色${index} DOM元素已添加到容器`);
            }
        });
        
        console.log('角色列表渲染完成，容器子元素数量:', container.children.length);
    } else {
        console.log('没有角色数据，显示"暂无数据"');
        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
        
        // 如果没有角色数据，尝试重新加载
        console.log('尝试重新加载角色数据...');
        loadRoles();
    }
}

// 确认角色选择
function confirmRoleSelection() {
    console.log('确认角色选择...');
    console.log('当前选中的角色ID:', advancedSelectedRoles);
    
    var displayText = '';
    var valueText = '';
    
    // 优先使用全局变量
    var currentRoleData = window.roleData || roleData || [];
    console.log('确认角色选择时使用的角色数据:', currentRoleData);
    
    if (advancedSelectedRoles.length === 0) {
        displayText = '请选择报工权限';
        valueText = '';
    } else {
        advancedSelectedRoles.forEach(roleId => {
            console.log('查找角色ID:', roleId);
            var role = currentRoleData.find(r => r.id == roleId); // 使用==比较，避免类型问题
            console.log('找到的角色:', role);
            if (role) {
                if (displayText) displayText += ', ';
                displayText += (roleId === 0 ? '所有人' : role.roleName);
                if (valueText) valueText += ',';
                valueText += roleId;
            }
        });
    }
    
    console.log('最终显示文本:', displayText);
    console.log('最终值文本:', valueText);
    
    document.getElementById('advancedReportingPermissions').innerHTML = '<span>' + displayText + '</span>';
    document.getElementById('advancedReportingPermissionsValue').value = valueText;
    
    closeRoleSelector();
}

// 关闭角色选择器
function closeRoleSelector() {
    console.log('关闭角色选择器弹窗...');
    
    // 使用Layui的layer模块关闭弹窗
    layui.use(['layer'], function(){
        var layer = layui.layer;
        
        // 获取当前打开的所有弹窗
        var openLayers = document.querySelectorAll('.layui-layer');
        if (openLayers.length > 0) {
            // 关闭最后一个弹窗（通常是当前弹窗）
            var lastLayer = openLayers[openLayers.length - 1];
            var layerIndex = lastLayer.getAttribute('times');
            if (layerIndex) {
                layer.close(layerIndex);
            }
        }
        
        // 确保隐藏原始DOM元素
        var modal = document.getElementById('roleSelectorModal');
        if (modal) {
            modal.style.display = 'none';
        }
    });
}

// 显示高级查询不良品项选择器
function showAdvancedDefectiveSelector() {
    console.log('显示高级查询不良品项选择器');
    
    // 检查Layui是否可用
    if (typeof window.layui === 'undefined' && typeof layui === 'undefined') {
        console.warn('Layui未加载，使用备用弹窗方案');
        showFallbackModal('选择不良品项', document.getElementById('advancedDefectiveSelectorModal').innerHTML, '500px', '600px');
        loadAdvancedDefectiveList();
        return;
    }
    
    // 使用更兼容的方式调用Layui
    try {
        var layuiInstance = window.layui || layui;
        layuiInstance.use(['layer'], function(){
            var layer = layuiInstance.layer;
            
            if (layer && typeof layer.open === 'function') {
                var index = layer.open({
                    type: 1,
                    title: '选择不良品项',
                    content: document.getElementById('advancedDefectiveSelectorModal'),
                    area: ['500px', '600px'],
                    maxmin: false,
                    resize: false,
                    success: function(layero, index) {
                        console.log('高级查询不良品项选择器弹窗显示成功，索引:', index);
                        // 加载不良品项列表
                        loadAdvancedDefectiveList();
                    },
                    end: function() {
                        console.log('高级查询不良品项选择器弹窗关闭');
                        // 弹窗关闭后，确保隐藏原始DOM元素
                        var modal = document.getElementById('advancedDefectiveSelectorModal');
                        if (modal) {
                            modal.style.display = 'none';
                        }
                    }
                });
                
                console.log('高级查询不良品项选择器弹窗索引:', index);
            } else {
                console.error('Layer模块不可用，使用备用弹窗方案');
                showFallbackModal('选择不良品项', document.getElementById('advancedDefectiveSelectorModal').innerHTML, '500px', '600px');
                loadAdvancedDefectiveList();
            }
        });
    } catch (error) {
        console.error('显示弹窗失败:', error);
        console.warn('使用备用弹窗方案');
        showFallbackModal('选择不良品项', document.getElementById('advancedDefectiveSelectorModal').innerHTML, '500px', '600px');
        loadAdvancedDefectiveList();
    }
}

// 预加载不良品项数据
function preloadDefectiveData() {
    console.log('开始预加载不良品项数据...');
    
    // 使用MVC控制器的GetDefectiveList方法
    fetch('/Process/GetDefectiveList?index=1&size=100')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                defectiveData = data.pageData || [];
                console.log('不良品项数据加载成功:', defectiveData);
                console.log('不良品项数据长度:', defectiveData.length);
            } else {
                console.error('加载不良品项失败:', data.msg);
                defectiveData = [];
            }
        })
        .catch(error => {
            console.error('加载不良品项失败:', error);
            defectiveData = [];
        });
}

// 加载高级查询不良品项列表
function loadAdvancedDefectiveList() {
    // 如果已有缓存数据，直接使用
    if (defectiveData && defectiveData.length > 0) {
        renderAdvancedDefectiveList(defectiveData);
        return;
    }
    
    // 使用MVC控制器的GetDefectiveList方法
    fetch('/Process/GetDefectiveList?index=1&size=100')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                defectiveData = data.pageData || [];
                renderAdvancedDefectiveList(defectiveData);
            } else {
                layer.msg(data.msg || '查询失败');
            }
        })
        .catch(error => {
            console.error('查询失败:', error);
            layer.msg('查询失败');
        });
}

// 渲染高级查询不良品项列表
function renderAdvancedDefectiveList(data) {
    var container = document.getElementById('advancedDefectiveList');
    container.innerHTML = '';
    
    if (data && data.length > 0) {
        data.forEach(item => {
            var div = document.createElement('div');
            div.className = 'layui-form-item';
            div.style.padding = '10px';
            div.style.borderBottom = '1px solid #eee';
            div.style.cursor = 'pointer';
            
            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.value = item.id;
            checkbox.checked = advancedSelectedDefectiveItems && advancedSelectedDefectiveItems.includes(item.id);
            checkbox.onchange = function() {
                if (this.checked) {
                    if (!advancedSelectedDefectiveItems.includes(item.id)) {
                        advancedSelectedDefectiveItems.push(item.id);
                    }
                } else {
                    advancedSelectedDefectiveItems = advancedSelectedDefectiveItems.filter(id => id !== item.id);
                }
            };
            
            div.appendChild(checkbox);
            div.appendChild(document.createTextNode(' ' + item.defectiveCode + ' | ' + item.defectiveName));
            
            container.appendChild(div);
        });
    } else {
        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
    }
}

// 搜索高级查询不良品项
function searchAdvancedDefective() {
    var searchText = document.getElementById('advancedDefectiveSearch').value;
    var url = '/Process/GetDefectiveList?index=1&size=100';
    
    if (searchText) {
        url += '&defectiveCode=' + encodeURIComponent(searchText) + '&defectiveName=' + encodeURIComponent(searchText);
    }
    
    // 使用MVC控制器的GetDefectiveList方法
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderAdvancedDefectiveList(data.pageData);
            } else {
                layer.msg(data.msg || '查询失败');
            }
        })
        .catch(error => {
            console.error('查询失败:', error);
            layer.msg('查询失败');
        });
}

// 关闭高级查询不良品项选择器
function closeAdvancedDefectiveSelector() {
    console.log('关闭高级查询不良品项选择器弹窗...');
    
    // 使用Layui的layer模块关闭弹窗
    layui.use(['layer'], function(){
        var layer = layui.layer;
        
        // 获取当前打开的所有弹窗
        var openLayers = document.querySelectorAll('.layui-layer');
        if (openLayers.length > 0) {
            // 关闭最后一个弹窗（通常是当前弹窗）
            var lastLayer = openLayers[openLayers.length - 1];
            var layerIndex = lastLayer.getAttribute('times');
            if (layerIndex) {
                layer.close(layerIndex);
            }
        }
        
        // 确保隐藏原始DOM元素
        var modal = document.getElementById('advancedDefectiveSelectorModal');
        if (modal) {
            modal.style.display = 'none';
        }
    });
}

// 获取工序的不良品项信息
function getProcessDefectiveItems(processId) {
    // 这里应该调用API获取工序的不良品项信息
    // 暂时返回空字符串，实际使用时需要实现API调用
    return '';
}

// 新建工序相关变量
var newProcessSelectedRoles = [];
var newProcessSelectedDefectiveItems = [];

// 重置新建工序表单
function resetNewProcessForm() {
    document.getElementById('newProcessForm').reset();
    newProcessSelectedRoles = [];
    newProcessSelectedDefectiveItems = [];
    
    // 重置显示文本
    document.getElementById('newProcessReportingPermissions').innerHTML = '<span style="color: #999;">请选择报工权限</span>';
    document.getElementById('newProcessDefectiveItemList').innerHTML = '<span style="color: #999;">请选择不良品项</span>';
    
    // 重置隐藏字段
    document.getElementById('newProcessReportingPermissionsValue').value = '';
    document.getElementById('newProcessDefectiveItemListValue').value = '';
    
    // 清空工序采集数据表格
    document.getElementById('newProcessCollectionDataTableBody').innerHTML = '';
}

// 关闭新建工序弹窗
function closeNewProcessModal() {
    console.log('关闭新建工序弹窗...');
    
    // 使用Layui的layer模块关闭弹窗
    layui.use(['layer'], function(){
        var layer = layui.layer;
        
        // 获取当前打开的所有弹窗
        var openLayers = document.querySelectorAll('.layui-layer');
        if (openLayers.length > 0) {
            // 关闭最后一个弹窗（通常是当前弹窗）
            var lastLayer = openLayers[openLayers.length - 1];
            var layerIndex = lastLayer.getAttribute('times');
            if (layerIndex) {
                layer.close(layerIndex);
            }
        }
        
        // 确保隐藏原始DOM元素
        var modal = document.getElementById('newProcessModal');
        if (modal) {
            modal.style.display = 'none';
        }
    });
}

// 显示新建工序角色选择器
function showNewProcessRoleSelector() {
    console.log('显示新建工序角色选择器');
    
    // 检查Layui是否可用
    if (typeof window.layui === 'undefined' && typeof layui === 'undefined') {
        console.warn('Layui未加载，使用备用弹窗方案');
        showFallbackModal('选择角色', document.getElementById('newProcessRoleSelectorModal').innerHTML, '400px', '500px');
        loadNewProcessRoleList();
        return;
    }
    
    // 使用更兼容的方式调用Layui
    try {
        var layuiInstance = window.layui || layui;
        layuiInstance.use(['layer'], function(){
            var layer = layuiInstance.layer;
            
            if (layer && typeof layer.open === 'function') {
                var index = layer.open({
                    type: 1,
                    title: '选择角色',
                    content: document.getElementById('newProcessRoleSelectorModal'),
                    area: ['400px', '500px'],
                    maxmin: false,
                    resize: false,
                    success: function(layero, index) {
                        console.log('新建工序角色选择器弹窗显示成功，索引:', index);
                        // 加载角色列表
                        loadNewProcessRoleList();
                    },
                    end: function() {
                        console.log('新建工序角色选择器弹窗关闭');
                        // 弹窗关闭后，确保隐藏原始DOM元素
                        var modal = document.getElementById('newProcessRoleSelectorModal');
                        if (modal) {
                            modal.style.display = 'none';
                        }
                    }
                });
                
                console.log('新建工序角色选择器弹窗索引:', index);
            } else {
                console.error('Layer模块不可用，使用备用弹窗方案');
                showFallbackModal('选择角色', document.getElementById('newProcessRoleSelectorModal').innerHTML, '400px', '500px');
                loadNewProcessRoleList();
            }
        });
    } catch (error) {
        console.error('显示弹窗失败:', error);
        console.warn('使用备用弹窗方案');
        showFallbackModal('选择角色', document.getElementById('newProcessRoleSelectorModal').innerHTML, '400px', '500px');
        loadNewProcessRoleList();
    }
}

// 加载新建工序角色列表
function loadNewProcessRoleList() {
    var container = document.getElementById('newProcessRoleList');
    container.innerHTML = '';
    
    console.log('loadNewProcessRoleList called, roleData:', roleData);
    console.log('window.roleData:', window.roleData);
    
    // 优先使用全局变量
    var currentRoleData = window.roleData || roleData || [];
    console.log('当前使用的角色数据:', currentRoleData);
    console.log('当前使用的角色数据长度:', currentRoleData ? currentRoleData.length : 'undefined');
    
    if (currentRoleData && currentRoleData.length > 0) {
        console.log('开始渲染新建工序角色列表...');
        currentRoleData.forEach((role, index) => {
            console.log(`处理新建工序角色${index}:`, role);
            console.log(`新建工序角色${index} ID:`, role.id, '类型:', typeof role.id);
            console.log(`新建工序角色${index} 名称:`, role.roleName);
            console.log(`新建工序角色${index} 状态:`, role.isState);
            console.log(`新建工序角色${index} 删除状态:`, role.isDeleted);
            
            // 检查角色是否应该显示
            var shouldShow = true;
            if (role.isState === false) {
                console.log(`新建工序角色${index} 状态为false，跳过`);
                shouldShow = false;
            }
            if (role.isDeleted === true) {
                console.log(`新建工序角色${index} 已删除，跳过`);
                shouldShow = false;
            }
            
            if (shouldShow) {
                console.log(`新建工序角色${index} 符合显示条件，创建DOM元素`);
                var div = document.createElement('div');
                div.className = 'layui-form-item';
                div.style.padding = '10px';
                div.style.borderBottom = '1px solid #eee';
                div.style.cursor = 'pointer';
                
                var checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.value = role.id;
                checkbox.checked = newProcessSelectedRoles && newProcessSelectedRoles.includes(role.id);
                checkbox.onchange = function() {
                    if (this.checked) {
                        if (!newProcessSelectedRoles.includes(role.id)) {
                            newProcessSelectedRoles.push(role.id);
                        }
                    } else {
                        newProcessSelectedRoles = newProcessSelectedRoles.filter(id => id !== role.id);
                    }
                };
                
                div.appendChild(checkbox);
                div.appendChild(document.createTextNode(' ' + (role.id === 0 ? '所有人' : role.roleName)));
                
                container.appendChild(div);
                console.log(`新建工序角色${index} DOM元素已添加到容器`);
            }
        });
        
        console.log('新建工序角色列表渲染完成，容器子元素数量:', container.children.length);
    } else {
        console.log('没有新建工序角色数据，显示"暂无数据"');
        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
        
        // 如果没有角色数据，尝试重新加载
        console.log('尝试重新加载新建工序角色数据...');
        loadRoles();
    }
}

// 确认新建工序角色选择
function confirmNewProcessRoleSelection() {
    console.log('确认新建工序角色选择...');
    console.log('当前选中的角色ID:', newProcessSelectedRoles);
    
    var displayText = '';
    var valueText = '';
    
    // 优先使用全局变量
    var currentRoleData = window.roleData || roleData || [];
    console.log('确认新建工序角色选择时使用的角色数据:', currentRoleData);
    
    if (newProcessSelectedRoles.length === 0) {
        displayText = '请选择报工权限';
        valueText = '';
    } else {
        newProcessSelectedRoles.forEach(roleId => {
            console.log('查找新建工序角色ID:', roleId);
            var role = currentRoleData.find(r => r.id == roleId); // 使用==比较，避免类型问题
            console.log('找到的新建工序角色:', role);
            if (role) {
                if (displayText) displayText += ', ';
                displayText += (roleId === 0 ? '所有人' : role.roleName);
                if (valueText) valueText += ',';
                valueText += roleId;
            }
        });
    }
    
    console.log('最终新建工序显示文本:', displayText);
    console.log('最终新建工序值文本:', valueText);
    
    document.getElementById('newProcessReportingPermissions').innerHTML = '<span>' + displayText + '</span>';
    document.getElementById('newProcessReportingPermissionsValue').value = valueText;
    
    closeNewProcessRoleSelector();
}

// 关闭新建工序角色选择器
function closeNewProcessRoleSelector() {
    console.log('关闭新建工序角色选择器弹窗...');
    
    // 使用Layui的layer模块关闭弹窗
    layui.use(['layer'], function(){
        var layer = layui.layer;
        
        // 获取当前打开的所有弹窗
        var openLayers = document.querySelectorAll('.layui-layer');
        if (openLayers.length > 0) {
            // 关闭最后一个弹窗（通常是当前弹窗）
            var lastLayer = openLayers[openLayers.length - 1];
            var layerIndex = lastLayer.getAttribute('times');
            if (layerIndex) {
                layer.close(layerIndex);
            }
        }
        
        // 确保隐藏原始DOM元素
        var modal = document.getElementById('newProcessRoleSelectorModal');
        if (modal) {
            modal.style.display = 'none';
        }
    });
}

// 显示新建工序不良品项选择器
function showNewProcessDefectiveSelector() {
    console.log('显示新建工序不良品项选择器');
    
    // 检查Layui是否可用
    if (typeof window.layui === 'undefined' && typeof layui === 'undefined') {
        console.warn('Layui未加载，使用备用弹窗方案');
        showFallbackModal('选择不良品项', document.getElementById('newProcessDefectiveSelectorModal').innerHTML, '500px', '600px');
        loadNewProcessDefectiveList();
        return;
    }
    
    // 使用更兼容的方式调用Layui
    try {
        var layuiInstance = window.layui || layui;
        layuiInstance.use(['layer'], function(){
            var layer = layuiInstance.layer;
            
            if (layer && typeof layer.open === 'function') {
                var index = layer.open({
                    type: 1,
                    title: '选择不良品项',
                    content: document.getElementById('newProcessDefectiveSelectorModal'),
                    area: ['500px', '600px'],
                    maxmin: false,
                    resize: false,
                    success: function(layero, index) {
                        console.log('新建工序不良品项选择器弹窗显示成功，索引:', index);
                        // 加载不良品项列表
                        loadNewProcessDefectiveList();
                    },
                    end: function() {
                        console.log('新建工序不良品项选择器弹窗关闭');
                        // 弹窗关闭后，确保隐藏原始DOM元素
                        var modal = document.getElementById('newProcessDefectiveSelectorModal');
                        if (modal) {
                            modal.style.display = 'none';
                        }
                    }
                });
                
                console.log('新建工序不良品项选择器弹窗索引:', index);
            } else {
                console.error('Layer模块不可用，使用备用弹窗方案');
                showFallbackModal('选择不良品项', document.getElementById('newProcessDefectiveSelectorModal').innerHTML, '500px', '600px');
                loadNewProcessDefectiveList();
            }
        });
    } catch (error) {
        console.error('显示弹窗失败:', error);
        console.warn('使用备用弹窗方案');
        showFallbackModal('选择不良品项', document.getElementById('newProcessDefectiveSelectorModal').innerHTML, '500px', '600px');
        loadNewProcessDefectiveList();
    }
}

// 关闭新建工序不良品项选择器
function closeNewProcessDefectiveSelector() {
    console.log('关闭新建工序不良品项选择器弹窗...');
    
    // 使用Layui的layer模块关闭弹窗
    layui.use(['layer'], function(){
        var layer = layui.layer;
        
        // 获取当前打开的所有弹窗
        var openLayers = document.querySelectorAll('.layui-layer');
        if (openLayers.length > 0) {
            // 关闭最后一个弹窗（通常是当前弹窗）
            var lastLayer = openLayers[openLayers.length - 1];
            var layerIndex = lastLayer.getAttribute('times');
            if (layerIndex) {
                layer.close(layerIndex);
            }
        }
        
        // 确保隐藏原始DOM元素
        var modal = document.getElementById('newProcessDefectiveSelectorModal');
        if (modal) {
            modal.style.display = 'none';
        }
    });
}

// 加载新建工序不良品项列表
function loadNewProcessDefectiveList() {
    // 如果已有缓存数据，直接使用
    if (defectiveData && defectiveData.length > 0) {
        renderNewProcessDefectiveList(defectiveData);
        return;
    }
    
    // 使用MVC控制器的GetDefectiveList方法
    fetch('/Process/GetDefectiveList?index=1&size=100')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                defectiveData = data.pageData || [];
                renderNewProcessDefectiveList(defectiveData);
            } else {
                layer.msg(data.msg || '查询失败');
            }
        })
        .catch(error => {
            console.error('查询失败:', error);
            layer.msg('查询失败');
        });
}

// 渲染新建工序不良品项列表
function renderNewProcessDefectiveList(data) {
    var container = document.getElementById('newProcessDefectiveList');
    container.innerHTML = '';
    
    if (data && data.length > 0) {
        data.forEach(item => {
            var div = document.createElement('div');
            div.className = 'layui-form-item';
            div.style.padding = '10px';
            div.style.borderBottom = '1px solid #eee';
            div.style.cursor = 'pointer';
            
            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.value = item.id;
            checkbox.checked = newProcessSelectedDefectiveItems && newProcessSelectedDefectiveItems.includes(item.id);
            checkbox.onchange = function() {
                if (this.checked) {
                    if (!newProcessSelectedDefectiveItems.includes(item.id)) {
                        newProcessSelectedDefectiveItems.push(item.id);
                    }
                } else {
                    newProcessSelectedDefectiveItems = newProcessSelectedDefectiveItems.filter(id => id !== item.id);
                }
            };
            
            div.appendChild(checkbox);
            div.appendChild(document.createTextNode(' ' + item.defectiveCode + ' | ' + item.defectiveName));
            
            container.appendChild(div);
        });
    } else {
        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
    }
}

// 确认新建工序不良品项选择
function confirmNewProcessDefectiveSelection() {
    console.log('确认新建工序不良品项选择...');
    console.log('当前选中的不良品项ID:', newProcessSelectedDefectiveItems);
    
    var displayText = '';
    var valueText = '';
    
    // 优先使用全局变量
    var currentDefectiveData = defectiveData || [];
    console.log('确认新建工序不良品项选择时使用的不良品项数据:', currentDefectiveData);
    
    if (newProcessSelectedDefectiveItems.length === 0) {
        displayText = '请选择不良品项';
        valueText = '';
    } else {
        newProcessSelectedDefectiveItems.forEach(itemId => {
            console.log('查找新建工序不良品项ID:', itemId);
            var item = currentDefectiveData.find(d => d.id == itemId); // 使用==比较，避免类型问题
            console.log('找到的新建工序不良品项:', item);
            if (item) {
                if (displayText) displayText += ', ';
                displayText += item.defectiveCode + ' | ' + item.defectiveName;
                if (valueText) valueText += ',';
                valueText += itemId;
            }
        });
    }
    
    console.log('最终新建工序不良品项显示文本:', displayText);
    console.log('最终新建工序不良品项值文本:', valueText);
    
    document.getElementById('newProcessDefectiveItemList').innerHTML = '<span>' + displayText + '</span>';
    document.getElementById('newProcessDefectiveItemListValue').value = valueText;
    
    closeNewProcessDefectiveSelector();
}

// 确认高级查询不良品项选择
function confirmAdvancedDefectiveSelection() {
    console.log('确认高级查询不良品项选择...');
    console.log('当前选中的不良品项ID:', advancedSelectedDefectiveItems);
    
    var displayText = '';
    var valueText = '';
    
    // 优先使用全局变量
    var currentDefectiveData = defectiveData || [];
    console.log('确认高级查询不良品项选择时使用的不良品项数据:', currentDefectiveData);
    
    if (advancedSelectedDefectiveItems.length === 0) {
        displayText = '请选择不良品项';
        valueText = '';
    } else {
        advancedSelectedDefectiveItems.forEach(itemId => {
            console.log('查找高级查询不良品项ID:', itemId);
            var item = currentDefectiveData.find(d => d.id == itemId); // 使用==比较，避免类型问题
            console.log('找到的高级查询不良品项:', item);
            if (item) {
                if (displayText) displayText += ', ';
                displayText += item.defectiveCode + ' | ' + item.defectiveName;
                if (valueText) valueText += ',';
                valueText += itemId;
            }
        });
    }
    
    console.log('最终高级查询不良品项显示文本:', displayText);
    console.log('最终高级查询不良品项值文本:', valueText);
    
    document.getElementById('advancedDefectiveItemList').innerHTML = '<span>' + displayText + '</span>';
    document.getElementById('advancedDefectiveItemListValue').value = valueText;
    
    closeAdvancedDefectiveSelector();
}

// 搜索新建工序不良品项
function searchNewProcessDefective() {
    var searchText = document.getElementById('newProcessDefectiveSearch').value;
    var url = '/Process/GetDefectiveList?index=1&size=100';
    
    if (searchText) {
        url += '&defectiveCode=' + encodeURIComponent(searchText) + '&defectiveName=' + encodeURIComponent(searchText);
    }
    
    // 使用MVC控制器的GetDefectiveList方法
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderNewProcessDefectiveList(data.pageData);
            } else {
                layer.msg(data.msg || '查询失败');
            }
        })
        .catch(error => {
            console.error('查询失败:', error);
            layer.msg('查询失败');
        });
}

// 搜索编辑工序不良品项
function searchEditProcessDefective() {
    var searchText = document.getElementById('editProcessDefectiveSearch').value;
    var url = '/Process/GetDefectiveList?index=1&size=100';
    
    if (searchText) {
        url += '&defectiveCode=' + encodeURIComponent(searchText) + '&defectiveName=' + encodeURIComponent(searchText);
    }
    
    // 使用MVC控制器的GetDefectiveList方法
    fetch(url)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                renderEditProcessDefectiveList(data.pageData);
            } else {
                layer.msg(data.msg || '查询失败');
            }
        })
        .catch(error => {
            console.error('查询失败:', error);
            layer.msg('查询失败');
        });
}

// 显示编辑工序弹窗
function showEditProcessModal(processId) {
    console.log('显示编辑工序弹窗，工序ID:', processId);
    
    // 这里应该加载工序数据并显示编辑弹窗
    // 暂时显示提示信息
    layer.msg('编辑工序功能待实现');
    
    // 实际编辑时应该调用：
    // fetch(`http://localhost:5089/api/Process/GetById/${processId}`)
    //     .then(response => response.json())
    //     .then(data => {
    //         if (data.code === 200) {
    //             // 填充编辑表单
    //             fillEditProcessForm(data.data);
    //             // 显示编辑弹窗
    //             showEditProcessModal();
    //         } else {
    //             layer.msg(data.msg || '获取工序数据失败');
    //         }
    //     })
    //     .catch(error => {
    //         console.error('获取工序数据失败:', error);
    //         layer.msg('获取工序数据失败');
    //     });
}

// 显示编辑工序角色选择器
function showEditProcessRoleSelector() {
    console.log('显示编辑工序角色选择器');
    
    // 这里应该显示编辑工序角色选择器弹窗
    // 暂时显示提示信息
    layer.msg('编辑工序角色选择器功能待实现');
}

// 显示编辑工序不良品项选择器
function showEditProcessDefectiveSelector() {
    console.log('显示编辑工序不良品项选择器');
    
    // 这里应该显示编辑工序不良品项选择器弹窗
    // 暂时显示提示信息
    layer.msg('编辑工序不良品项选择器功能待实现');
}

// 确认编辑工序角色选择
function confirmEditProcessRoleSelection() {
    console.log('确认编辑工序角色选择');
    
    // 这里应该确认编辑工序角色选择
    // 暂时显示提示信息
    layer.msg('确认编辑工序角色选择功能待实现');
}

// 确认编辑工序不良品项选择
function confirmEditProcessDefectiveSelection() {
    console.log('确认编辑工序不良品项选择');
    
    // 这里应该确认编辑工序不良品项选择
    // 暂时显示提示信息
    layer.msg('确认编辑工序不良品项选择功能待实现');
}

// 关闭编辑工序角色选择器
function closeEditProcessRoleSelector() {
    console.log('关闭编辑工序角色选择器');
    
    // 这里应该关闭编辑工序角色选择器弹窗
    // 暂时显示提示信息
    layer.msg('关闭编辑工序角色选择器功能待实现');
}

// 关闭编辑工序不良品项选择器
function closeEditProcessDefectiveSelector() {
    console.log('关闭编辑工序不良品项选择器');
    
    // 这里应该关闭编辑工序不良品项选择器弹窗
    // 暂时显示提示信息
    layer.msg('关闭编辑工序不良品项选择器功能待实现');
}

// 渲染编辑工序不良品项列表
function renderEditProcessDefectiveList(data) {
    var container = document.getElementById('editProcessDefectiveList');
    container.innerHTML = '';
    
    if (data && data.length > 0) {
        data.forEach(item => {
            var div = document.createElement('div');
            div.className = 'layui-form-item';
            div.style.padding = '10px';
            div.style.borderBottom = '1px solid #eee';
            div.style.cursor = 'pointer';
            
            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.value = item.id;
            checkbox.checked = false; // 编辑时默认不选中
            
            div.appendChild(checkbox);
            div.appendChild(document.createTextNode(' ' + item.defectiveCode + ' | ' + item.defectiveName));
            
            container.appendChild(div);
        });
    } else {
        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
    }
}

// 渲染编辑工序角色列表
function renderEditProcessRoleList(data) {
    var container = document.getElementById('editProcessRoleList');
    container.innerHTML = '';
    
    if (data && data.length > 0) {
        data.forEach(role => {
            var div = document.createElement('div');
            div.className = 'layui-form-item';
            div.style.padding = '10px';
            div.style.borderBottom = '1px solid #eee';
            div.style.cursor = 'pointer';
            
            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.value = role.id;
            checkbox.checked = false; // 编辑时默认不选中
            
            div.appendChild(checkbox);
            div.appendChild(document.createTextNode(' ' + (role.id === 0 ? '所有人' : role.roleName)));
            
            container.appendChild(div);
        });
    } else {
        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
    }
}

// 加载编辑工序角色列表
function loadEditProcessRoleList() {
    var container = document.getElementById('editProcessRoleList');
    container.innerHTML = '';
    
    // 优先使用全局变量
    var currentRoleData = window.roleData || roleData || [];
    
    if (currentRoleData && currentRoleData.length > 0) {
        currentRoleData.forEach((role, index) => {
            // 检查角色是否应该显示
            var shouldShow = true;
            if (role.isState === false) {
                shouldShow = false;
            }
            if (role.isDeleted === true) {
                shouldShow = false;
            }
            
            if (shouldShow) {
                var div = document.createElement('div');
                div.className = 'layui-form-item';
                div.style.padding = '10px';
                div.style.borderBottom = '1px solid #eee';
                div.style.cursor = 'pointer';
                
                var checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.value = role.id;
                checkbox.checked = false; // 编辑时默认不选中
                
                div.appendChild(checkbox);
                div.appendChild(document.createTextNode(' ' + (role.id === 0 ? '所有人' : role.roleName)));
                
                container.appendChild(div);
            }
        });
    } else {
        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无数据</div>';
    }
}

// 备用弹窗方案 - 当Layui不可用时使用
function showFallbackModal(title, content, width, height) {
    console.log('使用备用弹窗方案:', title);
    
    // 创建遮罩层
    var overlay = document.createElement('div');
    overlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
    `;
    
    // 创建弹窗容器
    var modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: ${width || '600px'};
        height: ${height || '400px'};
        background: white;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        overflow: auto;
    `;
    
    // 创建弹窗标题
    var header = document.createElement('div');
    header.style.cssText = `
        padding: 15px 20px;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
    `;
    header.innerHTML = `
        <h3 style="margin: 0; color: #1E9FFF;">${title}</h3>
        <button onclick="closeFallbackModal()" style="background: none; border: none; font-size: 20px; cursor: pointer; color: #999;">×</button>
    `;
    
    // 创建弹窗内容
    var body = document.createElement('div');
    body.style.cssText = 'padding: 20px;';
    body.innerHTML = content;
    
    // 组装弹窗
    modal.appendChild(header);
    modal.appendChild(body);
    
    // 添加到页面
    document.body.appendChild(overlay);
    document.body.appendChild(modal);
    
    // 存储引用以便关闭
    window.currentFallbackModal = { overlay: overlay, modal: modal };
}

// 关闭备用弹窗
function closeFallbackModal() {
    if (window.currentFallbackModal) {
        document.body.removeChild(window.currentFallbackModal.overlay);
        document.body.removeChild(window.currentFallbackModal.modal);
        window.currentFallbackModal = null;
    }
}

// 备用高级查询弹窗
function showFallbackAdvancedQuery() {
    var content = document.getElementById('advancedQueryModal').innerHTML;
    showFallbackModal('高级查询', content, '800px', '600px');
}

// 备用新建工序弹窗
function showFallbackNewProcess() {
    var content = document.getElementById('newProcessModal').innerHTML;
    showFallbackModal('工序(新建)', content, '1000px', '90vh');
}
</script>